<?php

namespace backend\modules\business\controllers;

use backend\controllers\BaseController;
use yii;
use yii\helpers\Url;
use common\models\SysShop;
use yii\data\Pagination;
use common\models\SysAgent;
use common\models\SysUser;
use common\models\BusConfig;
use yii\base\Object;
/**
 * 店面增删改查 (老板操作)
 * @author      futao
 * @date        2016-2-1
 * @version     2.0
 * @copyright   Copyright 2016 meelier.com
 */
class ShopmanageController extends BaseController
{	
	public $layout = '/agent';
    public function actionIndex()
    {
        $this->redirect(Url::toRoute("shopmanage/list"));
    }  
    /**
     * 店面列表
     * @date: 2016-2-1 
     * @author: futao
     */
    public function actionList()
    {
    	$query = SysShop::find()
    	->select(['sys_shop.*','sys_user.login_name','sys_user.create_name'])
    	->where("sys_shop.status = ".SysShop::NORMAL." and sys_shop.boss_uid = ".$this->userInfo->uid)
    	->leftJoin('sys_user','shop_uid = uid');
    	$countquery = clone $query;
    	$pages=new Pagination(['totalCount' => $countquery->count(),'pageSize' => $this->pageNavLimit]);
    	$model=$query
    	->offset($pages->offset)
    	->limit($pages->limit)
    	->orderby("shop_id desc")
    	->asArray()->all();
    	return $this->render('list',['model'=>$model,'page'=>$pages]);
    }
    /**
     * 添加店面
     * @date: 2016-2-2 
     * @author: futao
     */
    public function actionAdd()
    {
    	if(!$this->request->isPost){
    		return $this->render('add',['model'=>(new SysShop())]);
    	}
    	$user_name = $this->request->post("user_name",'');
    	$user_pass = $this->request->post("user_pass",'');
    	$shop_name = $this->request->post("shop_name",'');
    	$phone = $this->request->post('phone','');
    	$info=SysUser::find()->where("login_name = '".$user_name."'")->one();
    	if($info){
    		$this->error("账号已注册！");
    	}
    	if(empty($user_name) || empty($user_pass) || empty($shop_name)){
    		$this->error("参数不完整！");
    	}
    	$transaction = Yii::$app->db->beginTransaction();
    	try{
	    	$userModel = new SysUser();
	    	$userModel->login_name = $user_name;
	    	$userModel->password = $this->strEncryption($user_pass);
	    	$userModel->user_type = 4;
	    	$userModel->create_uid = $this->userInfo->uid;
	    	$userModel->create_name = $this->userInfo->user_name;
	    	$userModel->mobile = $phone;
	    	$userModel->user_role = 4;
	    	$userModel->user_name = $user_name;
	    	$userModel->save(false);
			$shopModel = new SysShop();
			$shopModel->shop_uid = $userModel->uid;
	    	$shopModel->shop_name = $shop_name;
	    	$shopModel->status = 1;
	    	$shopModel->boss_uid = $this->userInfo->boss_uid;
	    	$shopModel->boss_login_name = $this->userInfo->login_name;
	    	$shopModel->agent_uid = $this->userInfo->agent_uid;
	    	$shopModel->agent_login_name = $this->userInfo->agent_login_name;
	    	$shopModel->save(false);
	    	$this->initShopdata($shopModel->shop_id);
	    	$transaction->commit();
    	}catch(\Exception $e){
    		echo $e->getMessage(),$e->getLine();
    		$this->error("添加失败！");
    		$transaction->rollback();
    	}
        echo "<script>";
        echo "top.location.href='".Url::toRoute("shopmanage/list")."'";
        echo "</script>";
    } 
    /**
     * 编辑店面
     * @date: 2016-2-4
     * @author: futao
     */
    public function actionEdit()
    {
    	if(!$this->request->isPost){
    		$id = $this->request->get("id",0);
    		if($id<1){
    			$this->error("数据不存在！");
    		}
    		$shopInfo=SysShop::find()
    		->select([
				'sys_user.login_name',
    			'sys_user.user_name',
    			'sys_user.mobile',
    			'sys_shop.*'
    		])
    		->leftJoin("sys_user",'shop_uid = uid')
    		->where("shop_id = :id and boss_uid = :uid and sys_shop.status = ".SysShop::NORMAL,['id'=>$id,'uid'=>$this->userInfo->uid])
    		->asArray()->one();
    		if(!$shopInfo){
    			$this->error("数据不存在！");
    		}
    		return $this->render('edit',['shopInfo'=>$shopInfo]);
    	}
    	$user_pass = $this->request->post("user_pass",'');
    	$user_name = $this->request->post("user_name",'');
    	$shop_name = $this->request->post("shop_name",'');
    	$phone = $this->request->post('phone','');
    	$shopId = $this->request->post('id','');
    	$shopInfo = SysShop::find()
    	->where("boss_uid = :boss_id and shop_id = :shop_id",[':boss_id'=>$this->userInfo->boss_uid,':shop_id'=>$shopId])
    	->one();
    	if(!$shopInfo){
    		$this->error('参数错误!');
    	}
    	if(empty($shop_name)){
    		$this->error("参数不完整！");
    	}
    	$transaction = Yii::$app->db->beginTransaction();
    	try{
    		$userInfo = SysUser::findOne($shopInfo->shop_uid);
    		if($shopInfo->shop_uid==''){//新增店长
    			if($user_name!='' && $user_pass!=''){
	    			$info=SysUser::find()->where("login_name = '".$user_name."'")->one();
	    			if($info){
	    				$this->error("账号已注册！");
	    			}
	    			$userInfo = new SysUser;
	    			$userInfo->password = $this->strEncryption($user_pass);
	    			$userInfo->user_role = 4;
	    			$userInfo->user_type = 4;
	    			$userInfo->create_uid = $this->userInfo->uid;
	    			$userInfo->create_name = $this->userInfo->user_name;
	    			$userInfo->status = 1;
	    			$userInfo->login_name = $user_name;
	    			$userInfo->mobile = $phone;
	    			$userInfo->save(false);
	    			$shopInfo->shop_uid = $userInfo->uid;
    			}
    		}else{//修改店长
    			$userInfo = SysUser::findOne($shopInfo->shop_uid);
    			if($user_name!=''){
	    			$info=SysUser::find()->where("login_name = '".$user_name."' and uid != ".$shopInfo->shop_uid)->one();
	    			if($info){
	    				$this->error("账号已注册！");
	    			}
    			}
    			if($user_pass!=''){
    				$userInfo->password = $this->strEncryption($user_pass);
    			}
    			$userInfo->login_name = $user_name;
    			$userInfo->mobile = $phone;
    			$userInfo->status = 1;
    			$userInfo->save(false);
    		}
    		$shopInfo->shop_name = $shop_name;
    		$shopInfo->save(false);
    		$transaction->commit();
    	}catch(\Exception $e){
    		echo $e->getMessage()."--".$e->getLine();
    		$this->error("编辑失败！");
    		$transaction->rollback();
    	}
        echo "<script>";
        echo "top.location.href='".Url::toRoute("shopmanage/list")."'";
        echo "</script>";
    }  
     /**
     * 禁用账号
     * @date: 2016-2-4
     * @author: futao
     */
    public function actionDisable()
    {
    	$shopId = $this->request->get('id','');
    	$count = SysShop::find()
    	->where("boss_uid = :boss_id",[':boss_id'=>$this->userInfo->boss_uid])
    	->count();
    	if($count < 2){
    		$this->error('必须保留一家分店！');
    	}
    	$shopInfo = SysShop::find()
    	->where("boss_uid = :boss_id and shop_id = :shop_id",[':boss_id'=>$this->userInfo->boss_uid,':shop_id'=>$shopId])
    	->one();
    	if(!$shopInfo){
    		$this->error('参数错误!');
    	}
    	$transaction = Yii::$app->db->beginTransaction();
    	try{
    		$userInfo = SysUser::findOne($shopInfo->shop_uid);
    		if($userInfo){
    			$userInfo->login_name = '';
    			$userInfo->password = '';
    			$userInfo->status = 0;
    			$userInfo->save(false);
    		}
    		/* $shopInfo->status = 0;
    		$shopInfo->save(false); */
    		$transaction->commit();
    	}catch(\Exception $e){
    		$this->error("删除失败！");
    		$transaction->rollback();
    	}
    	$this->redirect(Url::toRoute("shopmanage/list"));
    }
    /**
     * 清空数据
     * @date: 2016年6月29日 
     * @author: chenxiaolin
     */
    public function actionCleardata(){
        $shop_id = $this->request->post("id",0);
        $state = $this->request->post("state",-10000);
        if(!in_array($state, [0,1])){
            $this->error('参数错误!');
        }
        $shopInfo = SysShop::find()
            ->where("boss_uid = :boss_id and shop_id = :shop_id",[':boss_id'=>$this->userInfo->boss_uid,':shop_id'=>$shop_id])
            ->one();
        if(!$shopInfo){
            $this->error('参数错误!');
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            //先禁用原分店：修改关联关系的店长Id(如加-)、复制当前分店信息
            $newShop = new SysShop();
            $newShop->shop_uid = $shopInfo->shop_uid;
            $newShop->shop_name = $shopInfo->shop_name;
            $newShop->status = $shopInfo->status;
            $newShop->start_time = $shopInfo->start_time;
            $newShop->end_time = $shopInfo->end_time;
            $newShop->boss_uid = $shopInfo->boss_uid;
            $newShop->boss_login_name = $shopInfo->boss_login_name;
            $newShop->agent_uid = $shopInfo->agent_uid;
            $newShop->agent_login_name = $shopInfo->agent_login_name;
            $newShop->create_time = $shopInfo->create_time;
            $newShop->isopen_online = 0;
            $newShop->remark = $shopInfo->remark;
            $newShop->save(false);
            //修改关联关系
            $shopInfo->shop_uid = intval('-'.$shopInfo->shop_uid);
            $shopInfo->status = 0;
            $shopInfo->save(false);
            $transaction->commit();
            if($state == 0){
                $rs = [
                    'status' => 10000,
                    'errmsg' => '分店数据已成功清空'
                ];
            }
            if($state == 1){
                $rs = [
                    'status' => 10000,
                    'errmsg' => '分店数据已成功清空，请联系客服重新开通线上店铺'
                ];
            }
            return json_encode($rs);
        } catch (\Exception $e) {
            $transaction->rollback();
            $rs = [
                'status' => -10000,
                'errmsg' => '清空失败,稍后再试！'
            ];
            return json_encode($rs);
        }
    }
    
    /**
     * 初始化店铺数据
     * @date: 2016-2-4
     * @author: futao
     */
    public function initShopdata($shopId)
    {
    	$shopInfo = SysShop::find()
    	->where("boss_uid = {$this->userInfo->boss_uid}")
    	->one();
    	$where[] = 'shop_id = '.$shopInfo->shop_id;
    	$whereStr = implode(' and ', $where);
    	$list = BusConfig::find()
    	->where($whereStr)
    	->asArray()->all();
    	$configModel = new BusConfig();
    	foreach ($list as $r){
    		$model = clone $configModel;
    		$model->shop_id = $shopId;
    		$model->config_type = $r['config_type'];
    		$model->config_key = $r['config_key'];
    		$model->config_val = $r['config_val'];
    		$model->config_val2 = $r['config_val2'];
    		if(!$model->save(false)){
    			throw new \Exception('初始化错误！');
    		}
    	}
    } 
}